import React, { memo } from 'react';
import { InputNumber } from 'antd';
import styles from './index.less';
import { connect } from 'react-redux';
import { findNodeById, formatPadding } from '@/utils';

function PaddingItem({ type, onChange, padding }: { type: string, padding: number[], onChange: (value: string) => void }) {
  let handleChange = function (value: string, index: number) {
    if (value === null) return;
    padding[index] = Number(value);
    onChange(padding.join(' '));
  }
  return (
    <>
      <div className={styles.propsTitle}>{type === 'inner' ? '内' : '外'}边距</div>
      <ul className={`${styles.wAndH} ${styles.padding}`}>
        {['上', '右', '下', '左'].map((item: string, index: number) => (
          <li key={item}>
            <label>{item}</label>
            <InputNumber
              min="0"
              defaultValue="0"
              className={styles.inputBox}
              value={padding[index].toString()}
              onChange={(value: string) => handleChange(value, index)}
            />
          </li>
        ))}
      </ul>
    </>
  );
}

function Padding(props: API.IPadding) {
  const { project, saveNodeChange } = props;
  const { currentCompId, pageConfig } = props.project;
  const currentNode = findNodeById(pageConfig, currentCompId);
  const style: React.CSSProperties = currentNode?.style || { padding: '0', margin: '0' };
  const padding: number[] = formatPadding(style.padding);
  const margin: number[] = formatPadding(style.margin);
  const handlePaddingChange = function (type: string, value: string) {
    console.log(type, '变动', value);
    if (value === null) return;
    saveNodeChange({
      id: currentCompId,
      style: {
        ...currentNode?.style,
        [type]: value
      }
    });
  };
  return (
    <>
      <PaddingItem type="inner" padding={padding} onChange={(value: string) => handlePaddingChange('padding', value)} />
      <PaddingItem type="outer" padding={margin} onChange={(value: string) => handlePaddingChange('margin', value)} />
    </>
  );
}

export default connect(
  ({ project }: any) => ({ project }),
  {
    saveNodeChange: (payload: { style: React.CSSProperties }) => ({ type: 'project/saveNodeChange', payload })
  }
)(memo(Padding));